"""
日记管理API路由
"""
import logging
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, desc

from app.database import get_db
from app.models.diary import Diary
from app.models.user import User
from app.schemas.diary import DiaryCreate, DiaryUpdate, Diary as DiarySchema, DiaryList
from app.schemas.ai import EmotionAnalysis

logger = logging.getLogger(__name__)

router = APIRouter()

# 暂时简化用户认证，实际项目中需要JWT认证
def get_current_user_id() -> int:
    """获取当前用户ID - 简化版本"""
    return 1  # 暂时返回固定用户ID


@router.post("/", response_model=DiarySchema, summary="创建日记")
async def create_diary(
    diary: DiaryCreate,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """创建新日记"""
    try:
        # 计算字数
        word_count = len(diary.content.replace(" ", "").replace("\n", ""))
        
        # 创建日记记录
        db_diary = Diary(
            user_id=current_user_id,
            title=diary.title,
            content=diary.content,
            tags=diary.tags or [],
            mood=diary.mood,
            word_count=word_count
        )
        
        db.add(db_diary)
        db.commit()
        db.refresh(db_diary)
        
        # 生成向量并保存到embedding表
        try:
            from app.services.embedding_service import embedding_service
            from app.models.embedding import Embedding
            
            # 对日记内容进行分块
            content_chunks = embedding_service.chunk_text(diary.content)
            
            # 为每个文本块生成向量
            embeddings = await embedding_service.create_embeddings(content_chunks)
            
            # 保存向量到数据库
            for i, (chunk, embedding_vector) in enumerate(zip(content_chunks, embeddings)):
                db_embedding = Embedding(
                    diary_id=db_diary.id,
                    content_chunk=chunk,
                    embedding=embedding_vector,
                    chunk_index=i
                )
                db.add(db_embedding)
            
            db.commit()
            logger.info(f"为日记 {db_diary.id} 创建了 {len(embeddings)} 个向量")
            
        except Exception as e:
            logger.warning(f"向量化失败，但日记创建成功: {str(e)}")
            # 向量化失败不影响日记创建
        
        return db_diary
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建日记失败: {str(e)}")


@router.get("/", response_model=List[DiaryList], summary="获取日记列表")
async def get_diaries(
    skip: int = Query(0, ge=0, description="跳过数量"),
    limit: int = Query(20, ge=1, le=100, description="返回数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    tags: Optional[str] = Query(None, description="标签筛选(逗号分隔)"),
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """获取日记列表"""
    try:
        query = db.query(Diary).filter(Diary.user_id == current_user_id)
        
        # 关键词搜索
        if keyword:
            query = query.filter(
                or_(
                    Diary.title.contains(keyword),
                    Diary.content.contains(keyword)
                )
            )
        
        # 标签筛选
        if tags:
            tag_list = [tag.strip() for tag in tags.split(",") if tag.strip()]
            if tag_list:
                # PostgreSQL JSON包含查询
                for tag in tag_list:
                    query = query.filter(Diary.tags.contains([tag]))
        
        # 按创建时间倒序
        query = query.order_by(desc(Diary.created_at))
        
        # 分页
        diaries = query.offset(skip).limit(limit).all()
        
        return diaries
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取日记列表失败: {str(e)}")


@router.get("/{diary_id}", response_model=DiarySchema, summary="获取日记详情")
async def get_diary(
    diary_id: int,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """获取指定日记详情"""
    diary = db.query(Diary).filter(
        and_(Diary.id == diary_id, Diary.user_id == current_user_id)
    ).first()
    
    if not diary:
        raise HTTPException(status_code=404, detail="日记不存在")
    
    return diary


@router.put("/{diary_id}", response_model=DiarySchema, summary="更新日记")
async def update_diary(
    diary_id: int,
    diary_update: DiaryUpdate,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """更新指定日记"""
    try:
        db_diary = db.query(Diary).filter(
            and_(Diary.id == diary_id, Diary.user_id == current_user_id)
        ).first()
        
        if not db_diary:
            raise HTTPException(status_code=404, detail="日记不存在")
        
        # 更新字段
        update_data = diary_update.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_diary, field, value)
        
        # 重新计算字数
        if diary_update.content:
            db_diary.word_count = len(diary_update.content.replace(" ", "").replace("\n", ""))
        
        db.commit()
        db.refresh(db_diary)
        
        # TODO: 重新生成向量
        
        return db_diary
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新日记失败: {str(e)}")


@router.delete("/{diary_id}", summary="删除日记")
async def delete_diary(
    diary_id: int,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """删除指定日记"""
    try:
        db_diary = db.query(Diary).filter(
            and_(Diary.id == diary_id, Diary.user_id == current_user_id)
        ).first()
        
        if not db_diary:
            raise HTTPException(status_code=404, detail="日记不存在")
        
        db.delete(db_diary)
        db.commit()
        
        return {"message": "日记删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除日记失败: {str(e)}")


@router.get("/{diary_id}/analyze", response_model=EmotionAnalysis, summary="分析日记情感")
async def analyze_diary_emotion(
    diary_id: int,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """分析指定日记的情感"""
    diary = db.query(Diary).filter(
        and_(Diary.id == diary_id, Diary.user_id == current_user_id)
    ).first()
    
    if not diary:
        raise HTTPException(status_code=404, detail="日记不存在")
    
    # TODO: 集成情感分析AI模型
    # 这里返回模拟数据
    return EmotionAnalysis(
        emotion="积极",
        confidence=0.85,
        mood_score=0.3,
        emotions_detail={
            "joy": 0.4,
            "sadness": 0.1,
            "anger": 0.05,
            "fear": 0.05,
            "surprise": 0.2,
            "neutral": 0.2
        }
    )